extends Area2D

# 方块的类型（用数字表示不同颜色）
@export var block_type: int = 0

# 添加一个新的变量来存储 ColorRect 节点
var overlay: ColorRect

signal swapped_with(other_block)

func _on_Block_input_event(viewport, event, shape_idx):
	if event is InputEventMouseButton and event.pressed:
		emit_signal("swapped_with", self)

# 初始化函数
func _ready():
	init_overlay()
	changeColor()
	set_sprite_size()


func init_overlay():
	overlay = ColorRect.new()
	overlay.color = Color(0, 0, 0, 0.5)
	overlay.size = Vector2(64, 64)
	overlay.position = Vector2(-32,-32);
	overlay.visible = false
	add_child(overlay)

func setOverlay(visible:bool):
	call_deferred("_hide_overlay", 0.2,visible)
	
func _hide_overlay(delay: float,visible:bool):
	await get_tree().create_timer(delay).timeout
	overlay.visible = visible

func changeColor():
	# 根据 block_type 设置图标
	match block_type:
		0:
			$Sprite2D.texture = preload("res://images/icon_0.png")
		1:
			$Sprite2D.texture = preload("res://images/icon_1.png")
		2:
			$Sprite2D.texture = preload("res://images/icon_2.png")
		3:
			$Sprite2D.texture = preload("res://images/icon_3.png")
		4:
			$Sprite2D.texture = preload("res://images/icon_4.png")
		_:
			$Sprite2D.texture = preload("res://images/icon_default.png")

# 设置 Sprite2D 的宽高为 64px
func set_sprite_size():
	var tween:Tween = get_tree().create_tween()
	
	var sprite = $Sprite2D
	if sprite.texture != null:
		# 计算缩放比例
		var scale_x = 64.0 / sprite.texture.get_width()
		var scale_y = 64.0 / sprite.texture.get_height()
		tween.tween_property(sprite,"scale",Vector2(scale_x, scale_y),1.2).from(Vector2(0.2,0.2)).set_ease(Tween.EASE_OUT).set_trans(Tween.TRANS_LINEAR)
		
